﻿using Microsoft.EntityFrameworkCore;
using System.Linq.Expressions;

namespace EMall.Query
{
    public class EfCoreQueryService<TDbContext> : QueryService
        where TDbContext : DbContext
    {
        protected TDbContext DbContext;
        public EfCoreQueryService(TDbContext dbContext)
        {
            ArgumentNullException.ThrowIfNull(dbContext, nameof(dbContext));
            DbContext = dbContext;
        }
        public override IQueryable<TEntity> GetQueryable<TEntity>() => DbContext.Set<TEntity>().AsQueryable();
        public override async Task<TEntity> GetAsync<TEntity, TKey>(TKey id)
        {
            return await GetQueryable<TEntity>().FirstOrDefaultAsync(o => o.Id.Equals(id));
        }
        public override async Task<List<TEntity>> GetListAsync<TEntity>()
        {
            return await GetQueryable<TEntity>().ToListAsync();
        }
        public override async Task<List<TEntity>> GetListAsync<TEntity>(Expression<Func<TEntity, bool>> predicate)
        {
            return await GetQueryable<TEntity>().Where(predicate).ToListAsync();
        }
    }
}
